const app = getApp();

Component({
    properties: {
        data: {
            type: Array,
            value: [],
            observer: function(newVal, oldVal) {
                this.resetRight(newVal);
                this.checkedHandler();
            }
        },
        bids: {
            type: String,
            value: '',
            observer: function(newVal) {
                if (newVal) {
                    wx.setStorageSync('bids', newVal);
                }
            }
        },
        config: {
            type: Object,
            value: {
                multiple: false, // 如果是从筛选过来，应该是开启多选功能
            }
        }
    },
    data: {
        list: [], // 品牌列表数据
        rightArr: [], // 右侧字母展示
        jumpNum: '', //跳转到那个字母
        topGroup: [], // 内容高度数据
        keywords: '',
        listIndex: 0,
        scrollTop: 0,
        moveDistance: 0,
        checkedList: [], // 已选中的品牌
        brandsId: '',
        scrollId: ''
    },
    methods: {
        resetRight(data) {
            const rightArr = [];
            const d = this.dataHandler(data);

            d.forEach(item => {
                rightArr.push(item.title);
            })

            this.setData({
                list: d,
                scrollTop: 0,
                rightArr
            }, () => {
                if (data.length != 0) {
                    this.queryMultipleNodes();
                }
            })
        },
        dataHandler(d) {
            const map = {}, list = [];
            const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#";

            if (d.length > 0) {
                d.sort((a, b) => a.name_e.localeCompare(b.name_e));
                d.forEach(v => {
                    const firstIndex = v.name_e.charAt(0).toUpperCase();//首字母

                    if (letters.indexOf(firstIndex) >= 0) {
                        if (!map[firstIndex]) {
                            map[firstIndex] = [];
                        }
                        
                        map[firstIndex].push({
                            name: v.name_e,
                            name_c: v.name_c,
                            bid: v.bid,
                            key: firstIndex
                        });
                    } else {
                        if (!map['#']) {
                            map['#'] = [];
                        }
                        map['#'].push({
                            name: v.name_e,
                            name_c: v.name_c,
                            bid: v.bid,
                            key: '#'
                        });
                    }
                });

                letters.split('').forEach(item => {
                    if (map[item]) {
                        list.push({
                            title: item,
                            items: map[item]
                        })
                    }
                    return list;
                });
            }

            return list;
        },
        checkedHandler() {
            const { list } = this.data;
            const checkedList = [], brandsId = [];

            if (list.length > 0) {
                list.forEach(item => {
                    item.items.forEach(v => {
                        if (this.data.bids && this.data.config.multiple) {
                            if (this.data.bids.indexOf(v.bid) >= 0) {
                                checkedList.push({
                                    name_e: v.name,
                                    name_c: v.name_c,
                                    bid: v.bid,
                                });
                                brandsId.push(v.bid);
                            }
                        }
                    });
                })

                this.setData({
                    checkedList,
                    brandsId: brandsId.join(',')
                })
            }
        },
        /**
         * 右侧字母点击事件
         */
        jumpMt(e) {
            let jumpNum = e.currentTarget.dataset.id;
            this.setData({
                jumpNum
            });
        },
        /**
         * 列表点击事件
         */
        detailMt(e) {
            let { detail } = e.currentTarget.dataset;
            let myEventOption = {
                bubbles: false, //事件是否冒泡
                composed: false, //事件是否可以穿越组件边界
                capturePhase: false //事件是否拥有捕获阶段
            } // 触发事件的选项

            if (!this.data.config.multiple) {
                this.triggerEvent('detail', detail, myEventOption)
            } else {
                this.delBrand(detail);
            }
        },
        // 基础搜索功能
        searchBrands(e) {
            const keywords = e.detail.value;

            this.setData({
                keywords
            })
            this._search();
        },
        /**
         * 搜索相关逻辑实现
         */
        _search() {
            const { keywords } = this.data;
            let data = this.data.data;
            let newData = this.data.data;
            if (keywords) {
                newData = data.filter(item => {
                    return item.name_e.toUpperCase().indexOf(keywords.toUpperCase()) >= 0 || item.name_c.indexOf(keywords) >= 0
                })
            }
            this.resetRight(newData);
        },
        /**
         * 监听滚动
         */
        scroll(e) {
            let top = e.detail.scrollTop
            let index = this.currentIndex(top)
            let list = this.data.topGroup
            let distance = top - list[this.data.listIndex]
            let num = -(list[this.data.listIndex + 1] - top - 66)
            // 渲染滚动索引
            if (index !== this.data.listIndex) {
                // console.log(index)
                this.setData({ 
                    listIndex: index,
                    moveDistance: 66,
                })
                // 如果监听到 index 的变化 ，一定要return ，否则吸顶会先变化文字后运动，会闪烁
                return
            }
            if (num <= 0) num = 0
            if (num !== this.data.moveDistance) {
                this.setData({
                    moveDistance: num,
                })
            }

            if (top <= 0) {
                this.setData({
                    moveDistance: 66,
                })
            }
        },
        /**
         * 获取当前滚动索引
         */
        currentIndex(y) {
            let listHeight = this.data.topGroup;
            for (let i = 0; i < listHeight.length; i++) {
                let height1 = listHeight[i]
                let height2 = listHeight[i + 1]
                if (y >= height1 && (y < height2 || !height2)) {
                    return i
                }
            }
            return 0
        },
        /**
         * 获取节点信息
         */
        queryMultipleNodes() {
          let self = this 
            const query = wx.createSelectorQuery().in(this);
            query.selectAll('.fixed-title-hock').boundingClientRect((res) => {
                res.forEach(function(rect) {
                    rect.top // 节点的上边界坐标
                })
            }).exec((e) => {
                let arr = []
                e[0].forEach((rect) => {
                    let num = 0
                    if (rect.top !== 0) {
                      num = rect.top - 66
                    }
                    arr.push(num)
                })
                this.setData({
                    topGroup: arr
                })
            })
        },
        formReset() {
            this.setData({
                listIndex: 0,
                keywords: ''
            })
            this._search();
        },
        // 删除选中品牌
        cancelBrand(e) {
            const { detail } = e.currentTarget.dataset;

            this.delBrand(detail);
        },
        delBrand(info) {
            let { checkedList, brandsId } = this.data;
            let ids = brandsId ? brandsId.split(',') : [];
            const index = checkedList.findIndex(item => item.bid == info.bid);

            if (index >= 0) {
                checkedList.splice(index, 1);
                ids.splice(index, 1);
            } else {
                checkedList.push({
                    bid: info.bid,
                    name_c: info.name_c,
                    name_e: info.name
                });
                ids.push(info.bid);
            }

            this.setData({
                checkedList,
                brandsId: ids.join(','),
                scrollId: `bid${ids[ids.length - 1]}`
            })
        },
        goFilterPage() {
            const { brandsId } = this.data;
            let myEventOption = {
                bubbles: false, //事件是否冒泡
                composed: false, //事件是否可以穿越组件边界
                capturePhase: false //事件是否拥有捕获阶段
            } // 触发事件的选项

            wx.setStorageSync('bids', brandsId);
            this.triggerEvent('backGetIds', brandsId, myEventOption)
        }
    }
})